package yxy.cherry.paycenter.servlet.channel.huawei;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.apple.util.Base64Utility;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_jh.PayMoudle_jh;
import yxy.cherry.paycenter.database.dao.orderinfoDao;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orderinfo;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.cherry.paycenter.util.HuaweiUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.module.OrderInfoModule;

/**
 * 验证信息 产生订单
 * @author Dell
 *
 */
public class Servlet_huawei2 extends Servlet{

	private static final Logger logger = Logger.create(Servlet_huawei2.class);
	private static final String checktokenurl = "https://orders-drcn.iap.hicloud.com/applications/purchases/tokens/verify";
	
	private static final int success = 1;	//成功
	private static final int noorder = 2;	//订单不存在
	private static final int failed = 3;	//失败
	
	private static final String responseCodesuccess = "0";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpUtil.printlnParseMap("post", req);
		JSONObject json = HttpUtil.getParseJSON(req);
		JSONObject rjson = new JSONObject();
		
//		{
//		    "autoRenewing": false,
//		    "orderId": "20201221185607119c8a6b3ff1.103401247",
//		    "packageName": "com.pm.ydsg.huawei",
//		    "applicationId": 103401247,
//		    "kind": 0,
//		    "productId": "90003",
//		    "productName": "元宝",
//		    "purchaseTime": 1608548209000,
//		    "purchaseTimeMillis": 1608548209000,
//		    "purchaseState": 0,
//		    "developerPayload": "20201221983185606951",
//		    "purchaseToken": "0000017684f1d7261052998914c1a6ff53d457982d5ef0847eac0da4c2d6c4b81063d8fe1789989cx434e.1.103401247",
//		    "consumptionState": 0,
//		    "confirmed": 0,
//		    "currency": "CNY",
//		    "price": 1,
//		    "country": "CN",
//		    "payOrderId": "Ac55d500e5905a078196e2517f078047",
//		    "payType": "4"
//		}
		
//		参数名称			必选(M)/可选(O)		数据类型		参数描述
//		purchaseToken	M					String		待下发商品的购买Token，发起购买和查询待消费商品信息时均会返回purchaseToken参数。
//		productId		M					String		待下发商品ID。商品ID来源于开发者在AppGallery Connect中配置商品信息时设置的“商品ID”。
		
		String developerPayload = json.getString("developerPayload");
		String productId = json.getString("productId");
		String purchaseToken = json.getString("purchaseToken");
		
		orders o = ordersDao.getOrderByMyorderid(developerPayload);
		if(o == null) {
			rjson.put("result", noorder);
			returnInfo(rjson, resp);
			return;
		}
		
		if(o.getOrderstate() == OrderInfoModule.orderinfofinish) {
			rjson.put("result", success);
			returnInfo(rjson, resp);
			return;
		}
		
		JSONObject postjson = new JSONObject();
		postjson.put("purchaseToken", purchaseToken);
		postjson.put("productId", productId);
		
        String response = null;
		try {
			response = HuaweiUtil.httpPost(checktokenurl, "application/x-www-form-urlencoded; charset=UTF-8", postjson.toString(), 5000, 5000, HuaweiUtil.buildAuthorization());
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.info("sdk_huawei2 response:" + response);
		JSONObject responsejson = JSON.parseObject(response);
		logger.info("sdk_huawei2 responsejson:" + responsejson);
		
		orderinfo orderinfo = new orderinfo();
		orderinfo.setMyorderid(developerPayload);
		orderinfo.setOtherinfo(response);
		orderinfoDao.add(orderinfo);
		
//		响应参数
//		参数名称		必选(M)/可选(O)		数据类型		参数描述
//		responseCode		M			String		返回码。●  0：成功 ●  其他：失败，具体参考接口错误码。
//		responseMessage		O			String		响应描述。
//		purchaseTokenData	O			String		包含购买数据的JSON字符串，具体参考表InAppPurchaseDetails。该字段原样参与签名。
//		dataSignature		O			String		purchaseTokenData基于应用RSA支付私钥的签名信息，签名算法为SHA256WITHRSA。
//													应用可以参考对响应消息验签的方法使用支付公钥对PurchaseTokenData的JSON字符串进行验签。
		
		String responseCode = responsejson.getString("responseCode");
		if(!responseCode.equals(responseCodesuccess)) {
			rjson.put("result", failed);
			returnInfo(rjson, resp);
			return;
		}
		
		String purchaseTokenData = responsejson.getString("purchaseTokenData");
		String dataSignature = responsejson.getString("dataSignature"); 
		
		String publicKey = "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAiAOD2dCdYKlXfrvjgTn3NzICyCRfZINmvoIF6HTYRlCeU5wYRJz8J9mdQIdZw5ps42R6fNk0NRHsxU8kMvW38BoreGypl47fkL6HlvvQXhd1gZ5mnjyxhj/OhmTstr/qJQY8+bqcyBfJolSDsszNNqsftzFCYD3WeR34HNewN1HYwq7L8sf8WUiJZGamvjvTacFlctfY49OqI+Eaf6NkEcHRTYHDfbscHF3u2lY8GegMi0XYOzoghlTlqI5guzgMHmM1BH0XREz6tEWePjx8VuT5XCWRtD7gd2i3viuuu8Juk9jQpsL7hiMGE1wIsPH2M5xPPnI7K5r53DOzdwYmu1/aUv+Ex0AKXM7h5QgnDUvnmmYDb4Ki5+yp9x4X2hod8+0+zFF6J5RHMJyCiLsJvQiwnGvyUJ/l12ao0mt3Dm+v3x2f1UlPbUxxbvTnR1NAZ9e0CaB74dvzXPdCcirXEtnM1CCuoGK2w/1u7KAEZTQkpSQuvUdFge7XfT/gFxhnAgMBAAE=";
		boolean check = doCheck(purchaseTokenData, dataSignature, publicKey);
		
		if(!check) {
			logger.info("sdk_huawei2 check:" + check);
			rjson.put("result", failed);
			returnInfo(rjson, resp);
			return;
		}
		
		JSONObject purchaseTokenDatajson = JSON.parseObject(purchaseTokenData);
		int price = purchaseTokenDatajson.getIntValue("price");
		String payOrderId = purchaseTokenDatajson.getString("payOrderId");
		
		o.setPlatorderid(payOrderId);
		o.setPayamount(price);
		o.setUpdatetime(new Date());
		o.setSubchannel(getChannel());
		o.setOrderstate(OrderInfoModule.orderinfofinish);
		ordersDao.update(o);
		
		ActType at = ActType.getat(o.getActtype());
//		PayType pt = PayType.getpt(at.getPaytype());
		PayMoudle_jh am = new PayMoudle_jh();
		ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());
		
		charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
		am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());
		rjson.put("result", success);
		returnInfo(rjson, resp);
	}
	
	/** *校验签名信息  
	* @param content 结果字符串  
	* @param sign 签名字符串  
	* @param publicKey 支付公钥  
	* @param是否校验通过  
	*/ 
	public static boolean doCheck(String content, String sign, String publicKey) { 
	    if ( sign == null) { 
	        return false; 
	    } 
	    if (publicKey == null) { 
	        return false; 
	    } 
	    try { 
	        KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
	        byte[] encodedKey = Base64Utility.decode(publicKey.getBytes()); 
	        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); 
	        java.security.Signature signature = null; 
	        signature = java.security.Signature.getInstance("SHA256WithRSA"); 
	        signature.initVerify(pubKey); 
	        signature.update(content.getBytes(StandardCharsets.UTF_8)); 
	        byte[] bsign = Base64Utility.decode(sign.getBytes()); 
	        return signature.verify(bsign); 
	    } catch (RuntimeException e) { 
	        throw e; 
	    } catch (Exception e) { 
	        e.printStackTrace(); 
	    } 
	    return false; 
	}    
	
	@Override
	public String getChannel() {
		return SdkChannel.sdk_huawei;
	}

	@Override
	public String getUrl() {
		return super.getUrl() + "2";
	}
	
}
